package com.auto.survey.activity.monitoring.ctrlmeasure

import android.content.Intent
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.auto.survey.R
import com.auto.survey.activity.monitoring.DoCollectedActivity
import com.auto.survey.activity.monitoring.IntentKey.KEY_INTENT_OBJECT_ID
import com.auto.survey.activity.monitoring.IntentKey.KEY_INTENT_PROJET_ID
import com.auto.survey.activity.monitoring.IntentKey.KEY_INTENT_STATION_ID
import com.auto.survey.activity.monitoring.IntentKey.KEY_INTENT_TASK_ID
import com.auto.survey.activity.monitoring.adapter.CtrlMeasureAdapter
import com.auto.survey.activity.monitoring.dao.MonitoringRepository
import com.auto.survey.activity.monitoring.entity.ctrlmeasure.ClosedLoopObservation
import com.auto.survey.base.BaseActivity
import com.auto.survey.widget.CentreToast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * 控制测量
 */
class CtrlMeasureActivity : BaseActivity() {
    private var projectId:Int = -1
    private var objectId:Int = -1
    private var stationId:Int = -1

    private val database = MonitoringRepository()

    private lateinit var adapter: CtrlMeasureAdapter

    override fun initView() {
        projectId = intent.getIntExtra(KEY_INTENT_PROJET_ID, -1)
        objectId = intent.getIntExtra(KEY_INTENT_OBJECT_ID, -1)
        stationId = intent.getIntExtra(KEY_INTENT_STATION_ID, -1)

        mTopBar?.visibility = View.VISIBLE
        mTopBar?.setBackgroundResource(R.color.action_bar)

        mComment_title?.visibility = View.VISIBLE
        mComment_title?.setBackgroundResource(R.color.action_bar)
        mComment_title?.setTitle("测量任务")

        findViewById<TextView>(R.id.tv_ctrl_to_pm).setOnClickListener {
            val intent = Intent()
            intent.putExtra(KEY_INTENT_PROJET_ID, projectId)
            intent.putExtra(KEY_INTENT_OBJECT_ID, objectId)
            intent.putExtra(KEY_INTENT_STATION_ID, stationId)
            intent.setClass(this@CtrlMeasureActivity, DoCollectedActivity::class.java)
            startActivity(intent)
        }
        findViewById<TextView>(R.id.tv_ctrl_creat).setOnClickListener {

            lifecycleScope.launch {
                database.getMonitoringPointClloectedByStationId(stationId).collect {
                    lifecycleScope.launch {
                        // 关键修复：使用firstOrNull()获取一次数据，而非collect()持续监听
                        val monitoringPoints =
                            database.getMonitoringPointClloectedByStationId(stationId).firstOrNull()
                                ?: emptyList()

                        val intent = Intent().apply {
                            putExtra(KEY_INTENT_PROJET_ID, projectId)
                            putExtra(KEY_INTENT_OBJECT_ID, objectId)
                            putExtra(KEY_INTENT_STATION_ID, stationId)
                        }

                        if (monitoringPoints.isEmpty()) {
                            AlertDialog.Builder(this@CtrlMeasureActivity)
                                .setTitle("提示")
                                .setMessage("没有添加测点，请先添加测点")
                                .setPositiveButton("确定") { dialog, _ ->
                                    intent.setClass(
                                        this@CtrlMeasureActivity,
                                        DoCollectedActivity::class.java
                                    )
                                    startActivity(intent)
                                    dialog.dismiss()
                                }
                                .setNegativeButton("取消") { dialog, _ ->
                                    dialog.dismiss()
                                }
                                .show()
                        } else {
                            intent.setClass(
                                this@CtrlMeasureActivity,
                                CtrlTaskAddActivity::class.java
                            )
                            startActivity(intent)
                        }
                    }
                }
            }

        }

        val recycler = findViewById<RecyclerView>(R.id.rv_ctrl_measure)
        recycler.layoutManager = LinearLayoutManager(this@CtrlMeasureActivity)
        adapter = CtrlMeasureAdapter()
        recycler.adapter = adapter
        adapter.setOnItemClickListener(object : CtrlMeasureAdapter.OnItemClickListenr{
            override fun onItemClick(item: ClosedLoopObservation, position: Int) {
                lifecycleScope.launch {
                    val data = database.getTaskPointList(item.id)
                    withContext(Dispatchers.Main) {
                        val intent = Intent()
                        if (data != null && data.points.isNotEmpty()) {
                            intent.putExtra(KEY_INTENT_PROJET_ID, projectId)
                            intent.putExtra(KEY_INTENT_OBJECT_ID, objectId)
                            intent.putExtra(KEY_INTENT_STATION_ID, stationId)
                            intent.putExtra(KEY_INTENT_TASK_ID, item.id)
                            intent.setClass(this@CtrlMeasureActivity, CtrlMeasureListActivity::class.java)
                            startActivity(intent)
                        } else {
                            intent.putExtra(KEY_INTENT_PROJET_ID, projectId)
                            intent.putExtra(KEY_INTENT_OBJECT_ID, objectId)
                            intent.putExtra(KEY_INTENT_STATION_ID, stationId)
                            intent.putExtra(KEY_INTENT_TASK_ID, item.id)
                            intent.setClass(this@CtrlMeasureActivity, CtrlMeasureManagerActivity::class.java)
                            startActivity(intent)
                        }
                    }
                }




            }

        })

    }

    override fun onResume() {
        super.onResume()
        lifecycleScope.launch {
            val datas = database.getStationWithClosedLoops(stationId)
            val closedloops =  datas?.points
            if (closedloops?.isNotEmpty() == true) {
                withContext(Dispatchers.Main) {
                    adapter.setItems(closedloops)
                }
            }
        }

    }

    override fun getLayoutId(): Int {

        return R.layout.activity_ctrl_measure
    }
}